import requests,json;
import mysql.connector;
import toke
import re
from tqdm import tqdm

class lieBian:

	#token='02e2c4aa-79a1-4d72-b914-eb2a5796f86a'
	

	def __init__(self,token,hd):
		self.token = token
		self.hd = hd

	def getPrantOpenid(self,openid):

		where={'access_token':self.token,'current':'1'}
		r=requests.get(
			'https://w.xiaoliebian.com/api/demo-wx-sys/v1/analysis/' + self.hd + '/user/'+openid+'/list'
			,params=where
		)

		data=json.loads(r.text)

		lists=[]

		if(data['success'] and data['code']==200):

			print('总页数=》',data['data']['list']['pages'])

			if(data['data']['list']['pages']>1):

				for i in range(1,data['data']['list']['pages']+1):

					where={'access_token':self.token,'current':i,'searchText':''}
					r=requests.get(
						'https://w.xiaoliebian.com/api/demo-wx-sys/v1/analysis/' + self.hd + '/user/'+openid+'/list'
						,params=where
					)

					data=json.loads(r.text)

					arr=data['data']['list']['records'];

					for list in arr:

						list['parent']=openid

					lists.extend(arr)

				self.upDb(lists,'opidchild',1,self.hd)

			else:

				lists=data['data']['list']['records']

				for list in lists:

					list['parent']=openid

				self.upDb(lists,'opidchild',1,self.hd)

		else:

			lists=[]

		return lists


	def getOpenidList(self):

		size=1000

		huodongId = self.hd

		where={'access_token':self.token,'current':1,'searchText':'','size':size}
		r=requests.get(
			'https://w.xiaoliebian.com/api/demo-wx-sys/v1/analysis/' + self.hd + '/user/list'
			,params=where
		)

		data=json.loads(r.text)


		list=[]

		if(data['success'] and data['code']==200):

			if(data['data']['list']['pages']>1):

				for i in tqdm(range(1,data['data']['list']['pages']+1)):

					print('总页数==>'+str(data['data']['list']['pages']+1))

					print('页数==>'+str(i))

					where={'access_token':self.token,'current':i,'searchText':'','size':size}
					r=requests.get(
						'https://w.xiaoliebian.com/api/demo-wx-sys/v1/analysis/' + self.hd + '/user/list'
						,params=where
					)

					data=json.loads(r.text)

					list.extend(data['data']['list']['records'])

					self.upDb(data['data']['list']['records'],"opidlist",2, huodongId )

					print('条目数==>'+str(len(list)))


					
			else:

				list=data['data']['list']['records']

				self.upDb(list,"opidlist",2,huodongId)

				print('条目数==>'+str(len(list)))


		else:

			list=[]



		return list

	def upDb(self,listData,table,type,huodongId):  #ListData要遍历的数组  table 要插入数据库表名  type 插入模式要 2 插入且更新 还是 1 忽略重复插入

		mydb = mysql.connector.connect(
		  host="localhost",       # 数据库主机地址
		  user="root",    # 数据库用户名
		  passwd="root",   # 数据库密码
		  database="liebian"
		)

		mycursor = mydb.cursor()
		upCount=0

		for i in tqdm(range(len(listData))):

			item=listData[i]
			val=[]
			filed=[]
			for key in item:
				nickname=''
				if(key=='nickname'):

					for reNa in item[key]:

						if(len(reNa.encode())<=3):
							nickname=nickname+reNa

					nickname=re.sub(r'[\"\'\/\\]', '', nickname, count=0, flags=0)

					val.append('\"{'+nickname+'}\"')

				else:
					
					val.append('\"'+str(item[''+key+''])+'\"')

				filed.append(key)

			filedStr=','.join(filed)
			valStr=','.join(val)
			# print(filedStr) INSERT IGNORE INTO 
			if(type==1):
				sql="REPLACE INTO "+table+"("+filedStr+',huodongid'+")value("+valStr+',\"'+ huodongId +"\");"
			elif(type==2):
				sql="REPLACE INTO "+table+"("+filedStr+',huodongid'+")value("+valStr+',\"'+ huodongId +"\");"
			print(sql+'\n')
			mycursor.execute(sql)
			mydb.commit()
			upCount=upCount+int(mycursor.rowcount)
		return upCount

	def getDb(self,quer):

		mydb = mysql.connector.connect(
		  host="localhost",       # 数据库主机地址
		  user="root",    # 数据库用户名
		  passwd="root",   # 数据库密码
		  database="liebian"
		)

		mycursor = mydb.cursor()
		mycursor.execute(quer)
		myresult = mycursor.fetchall()  

		return myresult

if __name__ == '__main__':

	tk=toke.toke()

	# try:

	lb=lieBian(tk.getToke('lb'),'e0dc4b236ba99560f21e9c7cb9649d37')#实例化对象

	# e0dc4b236ba99560f21e9c7cb9649d37 飞利浦活动1002
	# a60ce324395b5803427071c661f5ed27 飞利浦活动1003
	# a361010a3de8970e673298f3309ee64f 飞利浦活动1004

	# lb.getOpenidList(); #插入和更新当前参加人数的信息

	openids=lb.getDb('SELECT openId FROM opIdList WHERE num>0 AND huodongId=\'e0dc4b236ba99560f21e9c7cb9649d37\';') #获取父级openid
	
	i=0

	for i in tqdm(range(len(openids))): #遍历父级openid

		openid=openids[i]

		# try:

		dataArr=lb.getPrantOpenid(openid[0]) #获取父级下的子级信息
			
		# if(len(dataArr)>0):
			
		# 	print('总数：'+str(len(openids)))
		# 	print('进度：'+str(i))
		# 	print('子级更新==>'+str(lb.upDb(dataArr,'opIdChild',1))) #入库

		# except:

		# 	print('erro')

	# except:

	# 	print(tk.upLieBianToke());

		

		


